import { extend } from 'umi-request'
import { message, notification } from 'antd'
import { getLocale } from 'umi/locale'
import { getCurrentTenantId, getUserInfo } from './user'
import { getItem } from '@/utils/utils'
import { timeout } from '@/defaultSettings'

const codeMessage = {
  200: '服务器成功返回请求的数据。',
  201: '新建或修改数据成功。',
  202: '一个请求已经进入后台排队（异步任务）。',
  204: '删除数据成功。',
  400: '发出的请求有错误，服务器没有进行新建或修改数据的操作。',
  401: '用户没有权限（令牌、用户名、密码错误）。',
  403: '用户得到授权，但是访问是被禁止的。',
  404: '发出的请求针对的是不存在的记录，服务器没有进行操作。',
  406: '请求的格式不可得。',
  410: '请求的资源被永久删除，且不会再得到的。',
  422: '当创建一个对象时，发生一个验证错误。',
  500: '服务器发生错误，请检查服务器。',
  502: '网关错误。',
  503: '服务不可用，服务器暂时过载或维护。',
  504: '网关超时。',
}

/**
 * 异常处理程序
 */
function errorHandler(error) {
  try {
    const { resultCode, resultMsg } = JSON.parse(error.message)
    if (resultCode === '1') {
      if (resultMsg !== '')
        message.error(resultMsg)
    }
    else {
      notification.error({
        message: '系统内部异常，请联系管理员',
        description: resultMsg,
        placement: 'bottomRight',
      })
    }
    return Promise.reject(resultMsg)
  }
  catch (e) {
    throw error
  }
}

function getSessionId() {
  const bss3SessionId = getItem('bss3SessionId')

  if (bss3SessionId != null)
    return { bss3SessionId }

  return {}
}

// const getPrefix = url => {
//   if (parseQuery(window.location.href).API_HOST) {
//     requestUrl = `${parseQuery(window.location.href).API_HOST}${url}`;
//   } else {
//     requestUrl = window.API_HOST + url;
//   }
//   return /^http(s)?:\/\//.test(url) ? url : requestUrl;
// };

/**
 * 配置request请求时的默认参数
 */
const request = extend({
  // prefix: ,
  timeout,
  method: 'post',
  credentials: 'include', // 'same-origin' 默认值，同源时带cookies；'include' 同源和跨域都带cookies；'omit' 始终不带cookies
  errorHandler, // 默认错误处理
  headers: {
    ...getSessionId(),
    language: getLocale(),
    Accept: 'application/json',
    // 'Content-Type': 'application/json; charset=UTF-8',
  },
})

// 适配get类型$.ajax和umi-request传参挂载的key不一样的问题，前者是挂在data，后者是params
request.interceptors.request.use((url, options) => {
  const { data, method } = options

  // 全局HTTP请求拦截器，适配ng-portal

  // try-catch防止跨域报错
  try {
    const interceptor = top.window.tangramHttpInterceptor
    if (typeof interceptor === 'object' && typeof interceptor.beforeRequest === 'function') {
      const _options = interceptor.beforeRequest(options)
      if (_options.headers)
        options.headers = _options.headers
    }
  }
  catch (e) {
    console.warn(e)
  }

  if (method === 'get' && data !== undefined)
    options.params = data

  if (url === '/user/checkLogin' || url === '/user/login') {
    return {
      url: `v1${url}`,
      options,
    }
  }

  if (!getUserInfo() || !getUserInfo().isMultiTenant) {
    return {
      url: `v1${url}`,
      options,
    }
  }

  const tenantId = getCurrentTenantId()
  options.headers['X-TG-TenantId'] = tenantId

  return {
    url: `v1${url}`,
    options,
  }
})

// response拦截器, 可参考https://github.com/umijs/umi-request/issues/257
request.interceptors.response.use(async (response) => {
  if (response.status === 504) {
    throw new Error(
      JSON.stringify({ resultCode: '2', resultMsg: '504 (Gateway Timeout) 网关超时' }),
    )
  }
  return response
    .clone()
    .json()
    .then((responseJson) => {
      const { resultCode, resultMsg, resultData } = responseJson
      if (resultCode === '0')
        return resultData

      throw new Error(JSON.stringify({ resultCode, resultMsg }))
    })
})

export default request
